<?php
/**
 * 检查上一天编辑过的订单是否走结算流程
 * @author yiwan
 */

ini_set('display_errors', 1);
ini_set('memory_limit', -1);
error_reporting(-1);
require_once '/data/wwwroot/g_vendor/autoload.php';

use Doraemon\amqp\Queue;
use Biz\model\trade\Order as mOrder;
use Biz\model\trade\OrderGoods as mOrderGoods;
use Biz\model\trade\OrderRefund as mOrderRefund;
use Biz\module\Classes\SettlementTransaction as clsSettlementTransaction;
use Doraemon\tools\Log as toolsLog;
use Biz\tools\Mail;

$t1 = microtime(true);
var_dump('检查脚本开始时间：' . date('Y-m-d H:i:s'));

$startTime = date('Y-m-d', strtotime('-1 days'));
$endTime = date('Y-m-d H:i:s', strtotime("+1 days -1 second", strtotime($startTime)));
$orderList = mOrder::select('*', ['edittime[>=]' => $startTime, 'edittime[<=]' => $endTime]);
if ($orderList) {
    $orderNos = array_column($orderList, 'order_no');
//    $orderGoodsList = mOrderGoods::select('*', ['order_no' => $orderNos]);
//    $goodsList = [];
//    foreach ($orderGoodsList as $orderGoodsInfo) {
//        $goodsList[$orderGoodsInfo['order_no']][] = $orderGoodsInfo;
//    }
    $i = 0;
    foreach ($orderList as $orderInfo) {
        $orderNo = $orderInfo['order_no'];
        $status = $orderInfo['status'];
        checkTransaction($status, $orderInfo);

        var_dump('检查订单(' . ($i + 1) . ')：' . $orderNo . ' 结束');

//        foreach ($goodsList[$orderNo] as $goodsInfo) {
//
//        }
        $i++;
    }

    var_dump($startTime . '至' . $endTime . '订单，共检查' . $i . '个订单');

}
$t2 = microtime(true);
$time = $t2 - $t1;
$mtime = ($time * 1000);
var_dump('检查脚本结束时间：' . date('Y-m-d H:i:s'));
var_dump("检查脚本使用时间:" . number_format($time, 2) . '秒 ' . $mtime . '毫秒');


function checkTransaction($status, $orderInfo)
{
    switch ($status) {
        case mOrder::STATUS_NORMAL://已下单，待付款
            checkAfterCreateOrder($status, $orderInfo);
            break;
        case mOrder::STATUS_WAIT_SEND://已付款，待发货
        case mOrder::STATUS_SEND_OUT://已付款，已发货
        case mOrder::STATUS_SEND_PART_OUT://已付款，部分发货
            checkAfterCreateOrder($status, $orderInfo);
            checkAfterPaySuccess($status, $orderInfo);
            break;
        case mOrder::STATUS_SUCCESS://交易成功
            checkAfterCreateOrder($status, $orderInfo);
            checkAfterPaySuccess($status, $orderInfo);
            $refundList = [];
            checkAfterRefundSuccess($status, $orderInfo, $refundList);
            checkAfterConfirmOrder($status, $orderInfo, $refundList);
            break;
        case mOrder::STATUS_CLOSE://交易关闭
            checkAfterCreateOrder($status, $orderInfo);
            if ($orderInfo['pay_way'] && $orderInfo['pay_no']) {//已付款
                checkAfterPaySuccess($status, $orderInfo);
                $refundList = [];
                checkAfterRefundSuccess($status, $orderInfo, $refundList);
                if ($refundList) {
                    $refundSum = 0;
                    foreach ($refundList as $row) {
                        $refundSum = bcadd($refundSum, $row['refund_rmb'], 2);
                        $refundSum = bcadd($refundSum, $row['refund_shipping_amount'], 2);
                    }
                    //判断是否全部退款，如果是没退完，需要结算，走确认收货结算流程
                    if ($orderInfo['pay_amount'] != $refundSum && $refundSum < $orderInfo['pay_amount']) {
                        checkAfterConfirmOrder($status, $orderInfo, $refundList);
                    }
                }
            } else {//未付款
                checkAfterCancelOrder($status, $orderInfo);
            }
    }
}

function checkAfterCreateOrder($status, $orderInfo)
{
    $transactionClass = new clsSettlementTransaction();
    $result = $transactionClass->checkAfterCreateOrder($orderInfo['shop_id'], $orderInfo['order_no'], $orderInfo['integral_amount'], $orderInfo['coupon_amount'], $orderInfo['activity_allowance'], $orderInfo['packet_amount']);
    if (!$result) {
        $msg = '检查下单结算流程未执行';
        $errArr = [
            'order_no' => $orderInfo['order_no'],
            'uid' => $orderInfo['uid'],
            'status' => $status,
            'shop_id' => $orderInfo['shop_id'],
            'integral_amount' => $orderInfo['integral_amount'],
            'coupon_amount' => $orderInfo['coupon_amount'],
            'activity_allowance' => $orderInfo['activity_allowance'],
            'packet_amount' => $orderInfo['packet_amount'],
        ];
        toolsLog::settlement_checkTransaction_warning($msg, $errArr);
        Queue::insertQueue("queue/Wechatnotice/toTag", [
            "totag" => \Biz\pockets\constInterface\BizWechatTagConfig::TAG_BIZ_RD_SYSTEM,
            "content" => $msg . "#params:" . json_encode($errArr, JSON_UNESCAPED_UNICODE)
        ], Queue::QUEUE_BIZ);
        sendMail($msg, $msg . "#params:" . json_encode($errArr, JSON_UNESCAPED_UNICODE));
    }
}

function checkAfterCancelOrder($status, $orderInfo)
{
    $transactionClass = new clsSettlementTransaction();
    //检查是否有退款
    $result = $transactionClass->checkAfterCancelOrder($orderInfo['shop_id'], $orderInfo['order_no'], $orderInfo['integral_amount'], $orderInfo['coupon_amount'], $orderInfo['activity_allowance'], $orderInfo['packet_amount']);
    if (!$result) {
        $msg = '检查取消订单结算流程未执行';
        $errArr = [
            'order_no' => $orderInfo['order_no'],
            'uid' => $orderInfo['uid'],
            'status' => $status,
            'shop_id' => $orderInfo['shop_id'],
            'integral_amount' => $orderInfo['integral_amount'],
            'coupon_amount' => $orderInfo['coupon_amount'],
            'activity_allowance' => $orderInfo['activity_allowance'],
            'packet_amount' => $orderInfo['packet_amount'],
        ];
        toolsLog::settlement_checkTransaction_warning($msg, $errArr);
        Queue::insertQueue("queue/Wechatnotice/toTag", [
            "totag" => \Biz\pockets\constInterface\BizWechatTagConfig::TAG_BIZ_RD_SYSTEM,
            "content" => $msg . "#params:" . json_encode($errArr, JSON_UNESCAPED_UNICODE)
        ], Queue::QUEUE_BIZ);
        sendMail($msg, $msg . "#params:" . json_encode($errArr, JSON_UNESCAPED_UNICODE));
    }
}

function checkAfterPaySuccess($status, $orderInfo)
{
    $transactionClass = new clsSettlementTransaction();
    $result = $transactionClass->checkAfterPaySuccess($orderInfo['shop_id'], $orderInfo['order_no']);
    if (!$result) {
        $msg = '检查订单已付款结算流程未执行';
        $errArr = [
            'order_no' => $orderInfo['order_no'],
            'uid' => $orderInfo['uid'],
            'status' => $status,
            'shop_id' => $orderInfo['shop_id'],
        ];
        toolsLog::settlement_checkTransaction_warning($msg, $errArr);
        Queue::insertQueue("queue/Wechatnotice/toTag", [
            "totag" => \Biz\pockets\constInterface\BizWechatTagConfig::TAG_BIZ_RD_SYSTEM,
            "content" => $msg . "#params:" . json_encode($errArr, JSON_UNESCAPED_UNICODE)
        ], Queue::QUEUE_BIZ);
        sendMail($msg, $msg . "#params:" . json_encode($errArr, JSON_UNESCAPED_UNICODE));
    }
}

function checkAfterRefundSuccess($status, $orderInfo, &$refundList)
{
    $orderNo = $orderInfo['order_no'];
    $refundList = mOrderRefund::select('*', ['order_no' => $orderNo, 'status' => mOrderRefund::STATUS_COMPLETE, 'refund_amount[>]' => 0]);
    if ($refundList) {
        $transactionClass = new clsSettlementTransaction();
        foreach ($refundList as $refundInfo) {
            $result = $transactionClass->checkAfterRefundSuccess($orderInfo['shop_id'], $orderInfo['order_no'], $refundInfo['refund_order_no'], $refundInfo['refund_integral_amount'], $refundInfo['refund_coupon_amount'], $refundInfo['refund_activity_allowance'], $refundInfo['refund_packet_amount']);
            if (!$result) {
                $msg = '检查订单退款结算流程未执行';
                $errArr = [
                    'order_no' => $orderNo,
                    'uid' => $orderInfo['uid'],
                    'status' => $status,
                    'shop_id' => $orderInfo['shop_id'],
                    'refund_rmb' => $refundInfo['refund_rmb'],
                    'refund_order_no' => $refundInfo['refund_order_no'],
                    'refund_integral_amount' => $refundInfo['refund_integral_amount'],
                    'refund_coupon_amount' => $refundInfo['refund_coupon_amount'],
                    'refund_activity_allowance' => $refundInfo['refund_activity_allowance'],
                    'refund_packet_amount' => $refundInfo['refund_packet_amount'],
                    'refund_status' => $refundInfo['status']
                ];
                toolsLog::settlement_checkTransaction_warning($msg, $errArr);
                Queue::insertQueue("queue/Wechatnotice/toTag", [
                    "totag" => \Biz\pockets\constInterface\BizWechatTagConfig::TAG_BIZ_RD_SYSTEM,
                    "content" => $msg . "#params:" . json_encode($errArr, JSON_UNESCAPED_UNICODE)
                ], Queue::QUEUE_BIZ);
                sendMail($msg, $msg . "#params:" . json_encode($errArr, JSON_UNESCAPED_UNICODE));
            }
        }
    }
}

function checkAfterConfirmOrder($status, $orderInfo, $refundList)
{
    $transactionClass = new clsSettlementTransaction();
    if ($refundList) {//如果有退款，需要订单金额减去退款的各种金额来计算结算金额
        $refundSuccessSum = [
            'rmb' => 0,
            'integral_amount' => 0,
            'coupon_amount' => 0,
            'activity_allowance' => 0,
            'packet_amount' => 0,
            'commissions' => 0,
        ];

        foreach ($refundList as $row) {
            $refundSuccessSum['rmb'] = bcadd($refundSuccessSum['rmb'], $row['refund_rmb'], 2);
            $refundSuccessSum['rmb'] = bcadd($refundSuccessSum['rmb'], $row['refund_shipping_amount'], 2);

            $refundSuccessSum['integral_amount'] = bcadd($refundSuccessSum['integral_amount'], $row['refund_integral_amount'], 2);
            $refundSuccessSum['coupon_amount'] = bcadd($refundSuccessSum['coupon_amount'], $row['refund_coupon_amount'], 2);
            $refundSuccessSum['activity_allowance'] = bcadd($refundSuccessSum['activity_allowance'], $row['refund_activity_allowance'], 2);
            $refundSuccessSum['packet_amount'] = bcadd($refundSuccessSum['packet_amount'], $row['refund_packet_amount'], 2);
            $refundSuccessSum['commissions'] = bcadd($refundSuccessSum['commissions'], $row['refund_commission_amount'], 2);
        }

        $payAmount = bcsub($orderInfo['pay_amount'], $refundSuccessSum['rmb'], 2);
        $integralAmount = bcsub($orderInfo['integral_amount'], $refundSuccessSum['integral_amount'], 2);
        $couponAmount = bcsub($orderInfo['coupon_amount'], $refundSuccessSum['coupon_amount'], 2);
        $activityAllowance = bcsub($orderInfo['activity_allowance'], $refundSuccessSum['activity_allowance'], 2);
        $packetAmount = bcsub($orderInfo['packet_amount'], $refundSuccessSum['packet_amount'], 2);
        $commissions = bcsub($orderInfo['commissions'], $refundSuccessSum['commissions'], 2);

        $result = $transactionClass->checkAfterConfirmOrder($orderInfo['shop_id'], $orderInfo['order_no'], $integralAmount, $couponAmount, $activityAllowance, $packetAmount, $commissions);
        if (!$result) {
            $msg = '检查订单确认收货结算流程未执行';
            $errArr = [
                'order_no' => $orderInfo['order_no'],
                'uid' => $orderInfo['uid'],
                'status' => $status,
                'shop_id' => $orderInfo['shop_id'],
                'pay_amount' => $payAmount,
                'integral_amount' => $integralAmount,
                'coupon_amount' => $couponAmount,
                'activity_allowance' => $activityAllowance,
                'packet_amount' => $packetAmount,
                'commissions' => $commissions,
                'refund_success_sum' => $refundSuccessSum,
            ];
            toolsLog::settlement_checkTransaction_warning($msg, $errArr);
            Queue::insertQueue("queue/Wechatnotice/toTag", [
                "totag" => \Biz\pockets\constInterface\BizWechatTagConfig::TAG_BIZ_RD_SYSTEM,
                "content" => $msg . "#params:" . json_encode($errArr, JSON_UNESCAPED_UNICODE)
            ], Queue::QUEUE_BIZ);
            sendMail($msg, $msg . "#params:" . json_encode($errArr, JSON_UNESCAPED_UNICODE));
        }
    } else {
        $result = $transactionClass->checkAfterConfirmOrder($orderInfo['shop_id'], $orderInfo['order_no'], $orderInfo['integral_amount'], $orderInfo['coupon_amount'], $orderInfo['activity_allowance'], $orderInfo['packet_amount'], $orderInfo['commissions']);
        if (!$result) {
            $msg = '检查订单确认收货结算流程未执行';
            $errArr = [
                'order_no' => $orderInfo['order_no'],
                'uid' => $orderInfo['uid'],
                'status' => $status,
                'shop_id' => $orderInfo['shop_id'],
                'pay_amount' => $orderInfo['pay_amount'],
                'integral_amount' => $orderInfo['integral_amount'],
                'coupon_amount' => $orderInfo['coupon_amount'],
                'activity_allowance' => $orderInfo['activity_allowance'],
                'packet_amount' => $orderInfo['packet_amount'],
                'commissions' => $orderInfo['commissions']
            ];
            toolsLog::settlement_checkTransaction_warning($msg, $errArr);
            Queue::insertQueue("queue/Wechatnotice/toTag", [
                "totag" => \Biz\pockets\constInterface\BizWechatTagConfig::TAG_BIZ_RD_SYSTEM,
                "content" => $msg . "#params:" . json_encode($errArr, JSON_UNESCAPED_UNICODE)
            ], Queue::QUEUE_BIZ);
            sendMail($msg, $msg . "#params:" . json_encode($errArr, JSON_UNESCAPED_UNICODE));
        }
    }
}


function sendMail($title, $content)
{
    $sendMail = [
        'tangyiwan@haohaozhu.com',
    ];
    Mail::send($sendMail, $title, $content);
}


